﻿#region Copyrights Notice
//©2009 Microsoft Corporation.  All rights reserved.
//This portal design is based on the design and some code from DropThings.com which is also licensed under an MS-PL license.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;

using System.Configuration;
using System.Xml;
using System.Xml.Linq;
using AjaxControlToolkit;
using Microsoft.Security.Application;
using Microsoft.InformationSecurity.CISF.Portal.Business.PortalFramework;
using UTL = Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Common;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.RiskService;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.UserControls;


namespace Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Widgets
{
    public partial class Risks : System.Web.UI.UserControl, IWeblet
    {
        private IWebletContainer _WebletContainer;

        protected void Page_Load(object sender, EventArgs e)
        {
            //set the label text to nothing
            lblResults.Text = string.Format("");

            // Role CHECKING on every page load.
            if (!
                (
                // Not checking for Risk manager because Risk user is child of Risk manager.  
                // Parent inherits childs permissions.                
                     this.Context.User.IsInRole(ConfigurationManager.AppSettings["RiskEntryUser"].ToString())
                  || this.Context.User.IsInRole(ConfigurationManager.AppSettings["TrustedTaskUser"].ToString())
                )
               )
            {
                lblResults.Text = string.Format("You are not authorized to view the data.");
                gridMyRisks.Visible = false;
            }
            else
            {
                if (!
                (
                     (
                     this.Context.User.IsInRole(ConfigurationManager.AppSettings["RiskEntryUser"].ToString())
                  || this.Context.User.IsInRole(ConfigurationManager.AppSettings["RiskManager"].ToString())
                  )
                  &&
                  (this.Context.User.IsInRole(ConfigurationManager.AppSettings["TrustedTaskUser"].ToString()))
                )
               )
                    ViewState["isFilter"] = 0; // YES TO FILTER
                else
                    ViewState["isFilter"] = 1; // NO TO FILTER
            }
        }
        protected void LoadMyRisks(object sender, EventArgs e)
        {
        }

        #region Widget Implementation

        void IWeblet.OnControlInitilize(IWebletContainer host)
        {
            this._WebletContainer = host;
        }

        private XElement m_xmlStorage;
        private XElement State
        {
            get
            {
                if (m_xmlStorage == null)
                {
                    string tmpStr = string.Empty;
                    tmpStr = this._WebletContainer.Restore();
                    if (!tmpStr.Equals(string.Empty))
                        m_xmlStorage = XElement.Parse(tmpStr);
                }
                return m_xmlStorage;
            }
        }
        void IWebletActions.DisplaySettings(bool bDisplay)
        {
            SettingsPanel.Visible = bDisplay;
        }
        void ShowSettings()
        {
            SettingsPanel.Visible = true;
        }
        void HideSettings()
        {
            SettingsPanel.Visible = false;
        }

        void IWebletActions.Minimize()
        {
        }
        void IWebletActions.Maximize()
        {
        }
        void IWebletActions.Close()
        {

        }
        void IWebletActions.MaximizeToFullScreen()
        {

        }
        void IWebletActions.UpdateSettings()
        {

        }

        protected void SaveSettings_Click(object sender, EventArgs e)
        {
            this._WebletContainer.DisplaySettings(false);
        }

        private void SaveState()
        {
            if (this.State == null)
                return;

            StringBuilder builder = new StringBuilder();
            XmlTextWriter writer = new XmlTextWriter(new StringWriter(builder));
            this.State.WriteTo(writer);

            var xml = builder.ToString();
            this._WebletContainer.Save(xml);
        }

        #endregion


        #region My Risks Implementation

        /******************************
        Risks Implementation here...
        *******************************/

        private void BindGrid()
        {
            gridMyRisks.DataBind();
            if (HttpContext.Current.Items["risksRowCount"].ToString() == "0")
            {
                lblResults.Text = string.Format("No Active Risks.");
            }
        }

        protected void gridMyRisks_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (ViewState["GridSortDirection"] != null)
                if ((bool)ViewState["GridSortDirection"] == false)
                    ViewState["GridSortDirection"] = true;
                else
                    ViewState["GridSortDirection"] = false;
            else
                ViewState["GridSortDirection"] = false;
            ViewState["SortExpression"] = e.SortExpression;
            e.Cancel = true;

            this.BindGrid();
        }

        protected void gridMyRisks_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridMyRisks.PageIndex = e.NewPageIndex;
            this.BindGrid();
        }

        protected void risksSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {
            //setting number of days in past to filter risks
            int idatediff;
            try { idatediff = Int32.Parse(ConfigurationManager.AppSettings["MyRisksFilterDays"].ToString()); }
            // if someone tinkers with the value -;)
            catch { idatediff = 30; }

            string strEDDate = System.DateTime.UtcNow.ToString();
            string strSDDate = System.DateTime.UtcNow.AddDays(-idatediff).ToString();

            SearchFilterResult filterResult = new SearchFilterResult();
            filterResult.FieldName = "Risk Created Date";
            filterResult.Operator = "Between";
            filterResult.Values = new string[] { strSDDate, strEDDate };

            if (!e.ExecutingSelectCount)
            {
                e.Arguments.MaximumRows = gridMyRisks.PageSize;
                e.Arguments.StartRowIndex = (gridMyRisks.PageIndex * gridMyRisks.PageSize) + 1;
                e.InputParameters.Add("fieldName", filterResult.FieldName);
                e.InputParameters.Add("fieldoperator", filterResult.Operator);
                e.InputParameters.Add("value1", filterResult.Values[0]);
                if (filterResult.Values.Length > 1)
                    e.InputParameters.Add("value2", filterResult.Values[1]);
                else
                    e.InputParameters.Add("value2", null);

                if (ViewState["SortExpression"] == null)
                    e.InputParameters.Add("sortField", "RiskCreatedDate");
                else
                    e.InputParameters.Add("sortField", ViewState["SortExpression"]);
                e.InputParameters.Add("sortAscDesc", ViewState["GridSortDirection"]);
                e.InputParameters.Add("personID", ((CISF.Security.Principal.CISFIdentity)Page.User.Identity).PersonId);//Test Value: 47506
                e.InputParameters.Add("isRoleFilter", 0); // Always return User Risks based on Task User Role
            }
        }

        #endregion
    }

    public class RiskDataSource
    {
        public RiskDataSource()
        {

        }
        /// <summary>
        /// Get the count for the search records found.
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="fieldoperator"></param>
        /// <param name="sortField"></param>
        /// <param name="sortAscDesc"></param>
        /// <param name="value1"></param>
        /// <param name="value2"></param>
        /// <returns></returns>
        public int GetSearchResultCount
            (
            string fieldName,
            string fieldoperator,
            string sortField,
            int sortAscDesc,
            string value1,
            string value2,
            int personID,
            int isRoleFilter
            )
        {
            RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
            // Declare local variables.
            int totalCount = riskServiceClient.BasicSearchRiskCount
                (
                fieldName,
                fieldoperator,
                value1,
                value2,
                personID,
                isRoleFilter
                );
            riskServiceClient.Close();

            //set riskrowcount
            if (!HttpContext.Current.Items.Contains("risksRowCount"))
                HttpContext.Current.Items.Add("risksRowCount", totalCount);
            else
                HttpContext.Current.Items["risksRowCount"] = totalCount;

            //finally return the count
            return totalCount;
        }

        /// <summary>
        /// Gets the result for the search criteria.
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="fieldoperator"></param>
        /// <param name="sortField"></param>
        /// <param name="sortAscDesc"></param>
        /// <param name="value1"></param>
        /// <param name="value2"></param>
        /// <param name="maximumRows"></param>
        /// <param name="startRowIndex"></param>
        /// <returns></returns>
        public RiskInformation[] GetSearchResult(string fieldName, string fieldoperator, string sortField, int sortAscDesc, string value1, string value2, int maximumRows, int startRowIndex, int personID, int isRoleFilter)
        {
            RiskInformation[] riskCollection = null;
            try
            {
                RiskService.ManageRiskClient riskServiceClient = new RiskService.ManageRiskClient();
                // Declare local variables.
                riskCollection = riskServiceClient.BasicSearchRisk(fieldName, fieldoperator, sortField, sortAscDesc, maximumRows, startRowIndex, value1, value2, personID, isRoleFilter);
                riskServiceClient.Close();
            }
            catch (System.ServiceModel.Security.SecurityAccessDeniedException)
            {
                HttpContext.Current.Server.ClearError();
            }
            return riskCollection;
        }
    }

}